package com.sskj.fabi.ui.activity;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.PayBean;
import com.sskj.fabi.bean.PayWayBean;
import com.sskj.fabi.presenter.PublishActivityPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.FabiBuySellEnum;
import com.sskj.lib.bean.PayTypeEnum;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

@Route(path = RConfig.FABI_PUBLISH)
public class PublishActivity extends BaseActivity<PublishActivityPresenter> {
    @BindView(R2.id.segmentTabLayout)
    SegmentTabLayout segmentTabLayout;
    @BindView(R2.id.ivRecord)
    ImageView ivRecord;
    @BindView(R2.id.tvDesc)
    TextView tvDesc;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.etMin)
    EditText etMin;
    @BindView(R2.id.etMax)
    EditText etMax;
    @BindView(R2.id.etPrice)
    EditText etPrice;
    @BindView(R2.id.etRemark)
    EditText etRemark;
    @BindView(R2.id.remark_layout)
    LinearLayout remarkLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tvAddPayType)
    TextView tvAddPayType;
    @BindView(R2.id.llPayType)
    LinearLayout llPayType;
    @BindView(R2.id.btOrder)
    Button btOrder;

    boolean isBuy = true;

    private String[] titles = {App.INSTANCE.getString(R.string.fabi_publishActivity1_h) + FabiBuySellEnum.BUY.getTitle(), App.INSTANCE.getString(R.string.fabi_publishActivity1_h) + FabiBuySellEnum.SELL.getTitle()};
    private SlimAdapter slimAdapter;
    private HashMap<PayTypeEnum, Boolean> payMap = new HashMap<>();
    ;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_activity_publish;
    }

    @Override
    public PublishActivityPresenter getPresenter() {
        return new PublishActivityPresenter();
    }

    @Override
    protected void initView() {
        segmentTabLayout.setTabData(titles);
        segmentTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {

                if (position == 0 && !isBuy) {
                    isBuy = true;
                } else if (position == 1 && isBuy) {
                    isBuy = false;
                }
                changeUI();
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        initRecy();
        ClickUtil.click(tvDesc, () -> {
            TipUtil.getSureCancelTip(this, App.INSTANCE.getString(R.string.fabi_publishActivity2_h), App.INSTANCE.getString(R.string.fabi_publishActivity3_h), App.INSTANCE.getString(R.string.fabi_publishActivity4_h), () -> {
                mPresenter.cancelShop();
            });
        });
        ClickUtil.click(btOrder, () -> {
            if (checkParam()) {
                TipFabiUtil.showPublish(this, isBuy,
                        etPrice.getText().toString(),
                        etNum.getText().toString(), str -> {
                            mPresenter.requsetPublish(isBuy,
                                    etNum.getText().toString(),
                                    etMin.getText().toString(),
                                    etMax.getText().toString(),
                                    etPrice.getText().toString(),
                                    payMap.get(PayTypeEnum.WX) == null ? 0 : (payMap.get(PayTypeEnum.WX) ? 1 : 0),
                                    payMap.get(PayTypeEnum.ALIPAY) == null ? 0 : (payMap.get(PayTypeEnum.ALIPAY) ? 1 : 0),
                                    payMap.get(PayTypeEnum.BANK) == null ? 0 : (payMap.get(PayTypeEnum.BANK) ? 1 : 0),
                                    etRemark.getText().toString(), str[0]);
                        });


            }
        });
        ClickUtil.click(ivRecord, () -> {
            ARouter.getInstance().build(RConfig.FABI_PUBLISH_RECORD).navigation();
        });
        ClickUtil.click(tvAddPayType, () -> {
            ARouter.getInstance().build(RConfig.MINE_PAYMENT).navigation();
        });
        etMin.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        etMax.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        etPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
    }

    private void changeUI() {
        btOrder.setText(isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle());
        etNum.setHint(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity5_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        etPrice.setHint(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity6_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
        tvDesc.setText(String.format(App.INSTANCE.getString(R.string.fabi_publishActivity7_h), isBuy ? FabiBuySellEnum.BUY.getTitle() : FabiBuySellEnum.SELL.getTitle()));
    }

    @Override
    protected void onResume() {
        if (mPresenter != null) {
            mPresenter.requsetPayWayList();
        }
        super.onResume();
    }

    @Override
    protected void initData() {
        mPresenter.requsetPayWayList();
        mPresenter.requestUnitPrice();
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(etNum.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity8_h));
            return false;
        }
        if (TextUtils.isEmpty(etMin.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity9_h));
            return false;
        }
        if (TextUtils.isEmpty(etMax.getText())) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.fabi_publishActivity10_h));
            return false;
        }
        return true;
    }

    private void initRecy() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setLastDraw(false)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.fabi_232))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_pay_way, new SlimInjector<PayBean>() {
            @Override
            public void onInject(PayBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tvPayType, PayTypeEnum.getByType(data.getType()).getName())
                        .image(R.id.ivPayType, PayTypeEnum.getByType(data.getType()).getRes())
                        .with(R.id.checkbox, view -> {
                            CheckBox checkBox = (CheckBox) view;
                            checkBox.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.fabi_selector_checkbox, 0);
                        })
                        .checkChangeListener(R.id.checkbox, (buttonView, isChecked) -> {
                            payMap.put(PayTypeEnum.getByType(data.getType()), isChecked);
                        });
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());

    }

    public void updatePayWay(PayWayBean data) {
        ArrayList<PayBean> payBeans = new ArrayList<>();
        if (slimAdapter != null) {
            if (data.getWx() != null && !TextUtils.isEmpty(data.getWx().getStatus()) && !data.getWx().getStatus().equals("0")) {
                payBeans.add(new PayBean(data.getWx().getName(), data.getWx().getType()));
            }
            if (data.getAlipay() != null && !TextUtils.isEmpty(data.getAlipay().getStatus()) && !data.getAlipay().getStatus().equals("0")) {

                payBeans.add(new PayBean(data.getAlipay().getName(), data.getAlipay().getType()));
            }
            if (data.getBackcard() != null && !TextUtils.isEmpty(data.getBackcard().getStatus()) && !data.getBackcard().getStatus().equals("0")) {

                payBeans.add(new PayBean(data.getBackcard().getName(), data.getBackcard().getType()));
            }
            slimAdapter.updateData(payBeans);
//            Flowable.fromIterable(data)
//                    .subscribe(payWayBean -> payMap.put(PayTypeEnum.getByType(payWayBean.getType()), false));
//            slimAdapter.updateData(data);
        }

    }

    public void publishSuccess() {
        finish();
    }

    public void updatePrice(String price) {
        etPrice.setText(price);
    }

    public void cancelShopSuccess() {
        finish();
    }
}
